<?php

/**
 * adminusers actions.
 *
 * @package    retailbrain
 * @subpackage adminusers
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class adminusersActions extends sfActions {

    /**
     * Executes usuarios action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request) {

        $this->getResponse()->setSlot('title', 'Administración : Usuarios');
        $this->breadcrumbs = array(array("Administración", "admin/index"), array("Usuarios", "adminusers/index"));

        $q = Doctrine_Query::create()
                ->from('Users s')
                ->orderBy('s.name, s.last_name desc');

        $this->users = $q->fetchArray();

        $this->caps = $this->getUser()->getAttribute('caps');
    }

    /**
     * Executes editUsers action
     *
     * @param sfRequest $request A request object
     */
    public function executeEditUsers(sfWebRequest $request) {

        $id = $this->getRequestParameter('id');

        $this->getResponse()->setSlot('title', 'Administración : Editar Usuario');
        $this->breadcrumbs = array(array("Administración", "admin/index"), array("Usuarios", "adminusers/index"), array("Editar Usuario", "adminusers/editUsers?id=$id"));


        /** User **/
        $q = Doctrine_Query::create()
                ->from('Users u')
                ->where('u.id_users = ?', array($id))
                ->fetchArray();

        $this->user = $q;

        $q = Doctrine_Query::create()
                ->from('Capabilitys c')
                ->orderBy('c.id');

        $caps = $q->fetchArray();

        $dataCaps = array();
        foreach ($caps as $value) {
            if (myCapability::testcap($this->user[0]['caps'], myCapability::C($value['name']))) {
                $dataCaps[] = array($value['value'], "selected='selected'", $value['name']);
            } else {
                $dataCaps[] = array($value['value'], "", $value['name']);
            }
        }

        $this->caps = $dataCaps;
    }

    /**
     * Executes addUsers action
     *
     * @param sfRequest $request A request object
     */
    public function executeAddUsers(sfWebRequest $request) {

        $this->getResponse()->setSlot('title', 'Administración : Agregar Usuarios');
        $this->breadcrumbs = array(array("Administración", "admin/index"), array("Usuarios", "adminusers/index"), array("Agregar Usuario", "adminusers/addUsers"));

        $q = Doctrine_Query::create()
                ->from('Capabilitys c')
                ->orderBy('c.id');

        $this->caps = $q->fetchArray();
    }

    
    /**
     * Executes addUsers action
     *
     * @param sfRequest $request A request object
     */
    public function executeValUsers(sfWebRequest $request) {

        $this->setLayout(false);

        $username = $request->getParameter('users');

        $q = Doctrine_Query::create()
                ->from('Users u')
                ->where('u.username = ?', array($username['username']));

        $existe = count($q->fetchArray());

        if ($existe == 0) {
            $this->getResponse()->setContent(json_encode(true)); // Existe Usuario
        } else {
            $this->getResponse()->setContent(json_encode(false)); // No Existe Usuario
        }

        return sfView::NONE;
    }

    /**
     * Executes createUser action
     *
     * @param sfRequest $request A request object
     */
    public function executeCreateUser(sfWebRequest $request) {

        $_arrayPost = $request->getParameter('users');
        $_arrayCaps = $request->getParameter('capabilitys');

        /**
         * Capabilitys User 
         */
        $caps = 0;
        foreach ($_arrayCaps as $value) {
            $caps = myCapability::setcap($caps, $value);
        }

        try {

            $tabla = Doctrine::getTable('Users');
            $tabla = new Users();

            $tabla->name = $_arrayPost['name'];
            $tabla->last_name = $_arrayPost['last_name'];
            $tabla->email = $_arrayPost['email'];
            $tabla->phone_number = $_arrayPost['phone_number'];
            $tabla->username = $_arrayPost['username'];
            $tabla->password = md5($_arrayPost['password']);
            $tabla->caps = $caps;

            $tabla->creation_date = date('Y-m-d H:m:s');

            $tabla->deleted = 0;

            $tabla->save();
        } catch (Exception $e) {
            syslog(LOG_ERR, "Error: " . $e->getMessage());
        }

        $this->redirect('/adminusers/index');
    }

    /**
     * Executes updateUser action
     * 
     * @param sfWebRequest $request
     * @return type 
     */
    public function executeUpdateUser(sfWebRequest $request) {

        // Obtengo Datos del Formulario
        $_arrayPost = $request->getParameter('users');
        $_arrayCaps = $request->getParameter('capabilitys');

        /**
         * Capabilitys User 
         */
        $caps = 0;
        foreach ($_arrayCaps as $value) {
            $caps = myCapability::setcap($caps, $value);
        }

        try {

            $tabla = Doctrine::getTable('Users')->find(array($_arrayPost["id"]));

            $tabla->name = $_arrayPost['name'];
            $tabla->last_name = $_arrayPost['last_name'];
            $tabla->email = $_arrayPost['email'];
            $tabla->phone_number = $_arrayPost['phone_number'];
            $tabla->caps = $caps;

            if ($_arrayPost['password'] != '') {
                $tabla->password = md5($_arrayPost['password']);
            }

            $tabla->save();
        } catch (Exception $e) {
            syslog(LOG_ERR, "Error: " . $e->getMessage());
        }

        $this->redirect('adminusers/editUsers?id='.$_arrayPost["id"]);
    }

    /**
     * UserActive
     * [activo:inactivo]
     * @param sfWebRequest $request 
     */
    public function executeUpdateActiveUser(sfWebRequest $request) {

        // ID, Active
        $id = $request->getParameter('id');
        $active = $request->getParameter('active');
        $active = (($active == 0) ? 1 : 0);

        // Actualizo User
        $_data = Doctrine_Query::create()
                ->update('Users u')
                ->set('u.active', '?', $active)
                ->where('u.id_users = ?', array($id))
                ->execute();

        // all Users
        $q = Doctrine_Query::create()
                ->from('Users s')
                ->orderBy('s.name, s.last_name desc');

        $this->users = $q->fetchArray();

        $this->caps = $this->getUser()->getAttribute('caps');

        $this->setTemplate('lstUsers');
    }

    /**
     * UserDelete
     * [activo:inactivo]
     * @param sfWebRequest $request 
     */
    public function executeUpdateDeleteUser(sfWebRequest $request) {

        // ID, Active
        $id = $request->getParameter('id');
        $deleted = $request->getParameter('deleted');
        $deleted = (($deleted == 0) ? 1 : 0);

        // Actualizo User
        $_data = Doctrine_Query::create()
                ->update('Users u')
                ->set('u.deleted', '?', $deleted)
                ->where('u.id_users = ?', array($id))
                ->execute();

        // all Users
        $q = Doctrine_Query::create()
                ->from('Users s')
                ->orderBy('s.name, s.last_name desc');

        $this->users = $q->fetchArray();
        
        $this->caps = $this->getUser()->getAttribute('caps');


        $this->setTemplate('lstUsers');
    }

    
    
     /**
     * Executes editUsers action
     *
     * @param sfRequest $request A request object
     */
    public function executeEditUsersLocales(sfWebRequest $request) {
        
        $id = $this->getRequestParameter('id');

        $this->getResponse()->setSlot('title', 'Administración : Editar Usuario');
        $this->breadcrumbs = array(array("Administración", "admin/index"), array("Usuarios", "adminusers/index"), array("Editar Usuario", "adminusers/editUsers?id=$id"));
        

        /** User * */
        $q = Doctrine_Query::create()
                ->from('Users u')
                ->where('u.id_users = ?', array($id))
                ->fetchArray();

        $this->user = $q;

        $q = Doctrine_Query::create()
                ->from('Stores s')
                ->leftJoin('s.UserStores us')
                ->leftJoin('s.Regiones r')
                ->leftJoin('r.Provincias p')
                ->leftJoin('p.Comunas c');

        $this->stores = $q->fetchArray();
        
        
        
    }
    
    
    /**
     * Executes addChannels action
     *
     * @param sfRequest $request A request object
     */
    public function executeSetStoresPermissions(sfWebRequest $request) {

        $user = $request->getParameter('usuario');
        $stores = $request->getParameter('check');


        $deleted = Doctrine_Query::create()
                ->delete()
                ->from('UserStores')
                ->where('id_users = ?', array($user['id_users']))
                ->execute();

        foreach ($stores as $value) {

            try {

                $tabla = Doctrine::getTable('UserStores');
                $tabla = new UserStores();

                $tabla->id_store = $value;
                $tabla->id_users = $user['id_users'];

                $tabla->save();
            } catch (Exception $e) {
                syslog(LOG_ERR, "Error: " . $e->getMessage());
            }
        }

        $this->redirect('adminusers/editUsersLocales?id=' . $user['id_users']);
    }
}
